package com.yunbiao.ybbusstopplate.utils.core.screen;

import android.app.smdt.SmdtManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Environment;
import android.os.SystemProperties;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Surface;
import android.view.View;


import com.blankj.utilcode.util.ActivityUtils;
import com.example.library_hy_advert.system.Path;
import com.yunbiao.ybbusstopplate.base.APP;
import com.yunbiao.ybbusstopplate.base.BaseActivity;
import com.yunbiao.ybbusstopplate.base.HeartBeatClient;
import com.yunbiao.ybbusstopplate.utils.CommonUtils;
import com.yunbiao.ybbusstopplate.utils.core.NetTool;
import com.yunbiao.ybbusstopplate.utils.core.TYTool;
import com.yunbiao.ybbusstopplate.utils.core.logutils.LogUtils;
import com.yunbiao.ybbusstopplate.utils.core.power.JYDActions;
import com.yunbiao.ybbusstopplate.utils.core.power.ZHBroadControl;
import com.yunbiao.ybbusstopplate.utils.net.ResourceUpdate;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

import static android.content.ContentValues.TAG;

public class ScreenShot {

    private static ScreenShot screenShot = null;

    private ScreenShot() {
    }

    public static ScreenShot getInstanse() {
        if (screenShot == null) {
            synchronized (ScreenShot.class) {
                if (screenShot == null) {
                    screenShot = new ScreenShot();
                }
            }
        }
        return screenShot;
    }

    public void sendCutFinish(String sid, String filePath) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("sid", sid);
        NetTool.communication02(ResourceUpdate.SCREEN_UPLOAD_URL, params, filePath, "screenimage");
    }

    private void cutJDFScreenNew() {
        try {
            // 图片截取
            String path = new File(Path.getOnlineScreenCache(),"JDFScreen").getAbsolutePath();
            File jdf_file = new File(path);
            if (!jdf_file.exists()) {
                jdf_file.mkdirs();
            }
            String sid = HeartBeatClient.getDeviceNo();
            File imgfile = new File(path);
            for (File f : imgfile.listFiles()) {
                f.delete();
            }
            // 权限设置
            Process p = Runtime.getRuntime().exec("su");
            // 获取输出流
            OutputStream outputStream = p.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(
                    outputStream);
            // 将命令写入
            dataOutputStream.writeBytes("cd " + path + " && " + "sample_snap 1 " + path + "a.bmp");
            // 提交命令
            dataOutputStream.flush();
            // 关闭流操作
            dataOutputStream.close();
            outputStream.close();
            //计次，防止截屏失败无限循环
            int time = 0;
            while (!imgfile.exists() || imgfile.listFiles().length <= 0) {
                Thread.sleep(1000);
                time++;
                if (time > 5) {
                    time = 0;
                    break;
                }
            }
            if (imgfile.exists() && imgfile.listFiles().length > 0) {
                File f_01 = null;
                for (File f : imgfile.listFiles()) {
                    if (f.getName().contains(".bmp")) {
                        f_01 = f;
                        break;
                    }
                }
                if (f_01 != null && f_01.exists()) {
//                    Log.d("screenshot","imgfilepath:"+f_01.getAbsolutePath()+",size:"+f_01.length());
                    // 图片旋转并压缩
                    String absolutePath = f_01.getAbsolutePath();
                    changeImageRotationAndCompress(absolutePath);
                    // 图片上传
                    sendCutFinish(sid, absolutePath);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void changeImageRotationAndCompress(String filePath) throws IOException {
        int i = 0;
        String hwrotation = SystemProperties.get("persist.sys.hwrotation");
        if (!TextUtils.isEmpty(hwrotation)) {
            i = Integer.parseInt(hwrotation);
        } else {
            int rotation = ActivityUtils.getTopActivity().getWindowManager().getDefaultDisplay().getRotation();
            if (rotation == Surface.ROTATION_90) {
                i = 90;
            } else if (rotation == Surface.ROTATION_180) {
                i = 180;
            } else if (rotation == Surface.ROTATION_270) {
                i = 270;
            }
        }
        Bitmap decodeFile = BitmapFactory.decodeFile(filePath);
        if (decodeFile != null) {
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            if (i != 0) {
                Matrix matrix = new Matrix();
                matrix.postRotate(-i);
                decodeFile = Bitmap.createBitmap(decodeFile, 0, 0, decodeFile.getWidth(), decodeFile.getHeight(), matrix, true);
            }
            // 图片压缩
            decodeFile.compress(CompressFormat.JPEG, 20, fileOutputStream);
            fileOutputStream.close();

            decodeFile.recycle();
            decodeFile = null;
        }
    }

    private void cutA20Screen() {
        try {
            // 图片截取
            Process process = Runtime.getRuntime().exec("su");
            DataOutputStream dos = new DataOutputStream(process.getOutputStream());
            String path = Path.getOnlineScreenCache();
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            String sid = HeartBeatClient.getDeviceNo();
            String filePath = path + sid + ".png";
            File imageFile = new File(filePath);
            if (imageFile.exists()) {
                imageFile.delete();
            }
            dos.writeBytes("screencap -p " + filePath + "\n");
            dos.writeBytes("exit\n");
            process.waitFor();
            int temp = 0;
            while (!new File(filePath).exists()) {
                temp++;
                if (temp > 5) {
                    break;
                }
                Thread.sleep(1000);
            }
            if (new File(filePath).exists()) {
                // 图片旋转并压缩
                changeImageRotationAndCompress(filePath);
                // 图片上传
                sendCutFinish(sid, filePath);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void screencap() {
        try {
            if (ShellUtils.checkRootPermission() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                // 图片截取
                String path = Path.getOnlineScreenCache();
                File file = new File(path);
                if (!file.exists()) {
                    file.mkdirs();
                }
                String sid = HeartBeatClient.getDeviceNo();
                String filePath = path + sid + ".png";
                File imageFile = new File(filePath);
                if (imageFile.exists()) {
                    imageFile.delete();
                }
                ShellUtils.execCommand("/system/bin/screencap -p " + filePath, true, true);
                Thread.sleep(2000);
                // 图片旋转并压缩
                if (new File(filePath).exists()) {
                    Bitmap decodeFile = BitmapFactory.decodeFile(filePath);
                    if (Build.MODEL.contains("A40")) {
                        //A40 需要做下旋转
                        int displayRotation = CommonUtils.getDisplayRotation(ActivityUtils.getTopActivity());
                        if (displayRotation != 0) {
                            Matrix matrix = new Matrix();
                            matrix.postRotate(-displayRotation);
                            decodeFile = Bitmap.createBitmap(decodeFile, 0, 0, decodeFile.getWidth(), decodeFile.getHeight(), matrix, true);
                        }
                    }
                    FileOutputStream fileOutputStream = new FileOutputStream(filePath);
                    if (decodeFile != null && fileOutputStream != null) {
                        // 图片压缩
                        decodeFile.compress(CompressFormat.JPEG, 20, fileOutputStream);
                        // 图片上传
                        sendCutFinish(sid, filePath);
                        if (!decodeFile.isRecycled()) {
                            decodeFile.recycle();
                            decodeFile = null;
                        }
                    }
                }
            } else {
                cutYsScreen();
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void cutA83Screen() {
        cutYsScreen();
    }

    private void cutQingjiScreenTwo() {
        try {
            File pictures = new File(Path.getOnlineScreenCache(), "Pictures");
            String zhpath = new File(pictures,"Screenshots").getAbsolutePath();
            File pathFile = new File(zhpath);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            String imagePath = new File(zhpath,"picture.png").getAbsolutePath();
            String zhpath_s = new File(zhpath,"picture_s.jpg").getAbsolutePath();
            String sid = HeartBeatClient.getDeviceNo();
            File file = new File(imagePath);
            if (file.exists()) {
                file.delete();
            }
            File file_s = new File(zhpath_s);
            if (file_s.exists()){
                file_s.delete();
            }
            ShellUtils.execCommand("screencap " + imagePath, true, true);
            Thread.sleep(1000);
            if (file.exists()) {
                try {
                    Bitmap decodeFile = BitmapFactory.decodeFile(imagePath);
                    if (decodeFile != null) {
                        FileOutputStream fileOutputStream = new FileOutputStream(zhpath_s);
                        // 图片压缩
                        decodeFile.compress(CompressFormat.JPEG, 20, fileOutputStream);
                        fileOutputStream.close();
                        decodeFile.recycle();
                        decodeFile = null;
                        //传输压缩后的图片
                        sendCutFinish(sid, zhpath_s);
                        return;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //传输原始图片
                sendCutFinish(sid, imagePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void cutZhsdScreen() {
        String zhpath = "/mnt/internal_sd/Screenshots/";
        String sid = HeartBeatClient.getDeviceNo();
        String zhFilePath = zhpath + sid + ".png";
        File file = new File(zhFilePath);
        if (file.exists()) {
            file.delete();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ZHBroadControl.getZhBroadControl().screenCut(zhpath, sid);
        while (!new File(zhFilePath).exists()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        sendCutFinish(sid, zhFilePath);
    }

    private void cutYsScreen() {
        try {
            Bitmap bitmap = snapShotWithStatusBar();
            String path = Path.getOnlineScreenCache();
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            String sid = HeartBeatClient.getDeviceNo();
            String filePath = path + sid + ".png";
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            // 图片压缩
            bitmap.compress(CompressFormat.JPEG, 20, fileOutputStream);
            fileOutputStream.close();
            // 图片上传
            sendCutFinish(sid, filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 截屏,通用接口
    public Bitmap snapShotWithStatusBar() {
        View view = ActivityUtils.getTopActivity().getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        DisplayMetrics dm = new DisplayMetrics();
        ActivityUtils.getTopActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;  // 获取屏幕的宽  像素
        int height = dm.heightPixels; // 获取屏幕的高  像素
        Bitmap bp = Bitmap.createScaledBitmap(bmp, width, height, true);
//        Bitmap bp = Bitmap.createBitmap(bmp, 0, 0, width, height);

        view.destroyDrawingCache();
        return bp;
    }

    //建益达截屏
    private void cutJYDScreen() {
        String path = Path.getOnlineScreenCache();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String sid = HeartBeatClient.getDeviceNo();
        String filePath = path + sid + ".png";
        File imageFile = new File(filePath);
        if (imageFile.exists()) {
            imageFile.delete();
        }
        String cutPicPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/screenshot.png";
        File file1 = new File(cutPicPath);
        if (file1.exists()) {
            file1.delete();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        TYTool.sendBroadcast(JYDActions.SCREEN_CAP);
        int temp = 0;
        while (!new File(cutPicPath).exists()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            temp++;
            if (temp >= 5) {
                break;
            }
        }
        Log.d("screenshot", "path--->" + cutPicPath);
        try {
            Thread.sleep(3000);
            BitmapFactory.Options op = new BitmapFactory.Options();
            op.inSampleSize = 4; // 这个数字越大,图片就越小.图片就越不清晰
            Bitmap bitmap = BitmapFactory.decodeFile(cutPicPath, op);
            if (bitmap != null) {
                FileOutputStream fileOutputStream = new FileOutputStream(filePath);
                // 图片压缩
                bitmap.compress(CompressFormat.JPEG, 50, fileOutputStream);
                fileOutputStream.close();
                cutPicPath = filePath;
                bitmap.recycle();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        sendCutFinish(sid, cutPicPath);// 图片上传
    }

    /**
     * 屏幕截图
     * 0其他（国威）  1中恒  2深圳鸿世达科技  3亿晟科技  4小百合  5建益达  6庆吉 7京东方画屏
     */
    public void shootScreen() {
        Integer type = CommonUtils.getBroadType();
        switch (type.intValue()) {
            case 6:
                cutQingjiScreenTwo();//庆吉截屏(测试)
                break;
            case 4:
                cutJYDScreen();
                break;
            case 1:
                cutZhsdScreen();
                break;
            case 5:
                cutJYDScreen();
                break;
            case 3:
                cutYsScreen();
                break;
            case 7:
                cutJDFScreenNew();
                break;
//            case 8:
//                ChuangweiScreenShotService.screenShot();
//                break;
            default:
                SmdtManager smdt = APP.Companion.getSmdt();
                String androidModel = "";
                if (smdt != null) {
                    androidModel = smdt.getAndroidModel();
                }
                LogUtils.e(TAG, "AndroidModel: " + androidModel);
                switch (androidModel) {
                    case "SoftwinerEvb":
                        cutA20Screen();
                        break;
                    case "DS83X":
                        cutA83Screen();//无法截视频画面
                        break;
                    default:
                        screencap();
                        break;
                }
                break;
        }
    }
}
